<template>
	<div class="layout-container">
		<div class="left-container">
			<div class="top-left">
				<div class="label-button-wrapper">
					<span class="point-list-label">测点列表</span>
					<!-- <el-button type="primary" style="margin-right: 30px; margin-left: 30px; " @click="getPoints" >获取所有测点</el-button> -->
				</div>
				<el-input
					style="margin-right: 10px; margin-left: 200px"
					placeholder="输入遥测名称筛选"
					v-model="searchKey"
					size="small"
					@input="filterTree"
				></el-input>
			</div>
			<div class="bottom-left">
				<el-tree
					class="tree-with-scroll"
					:data="treeData"
					node-key="id+index"
					@node-click="handleNodeClick"
					:props="defaultProps"
					show-checkbox
					ref="treeNode"
					:default-expand-all="treeIsExpand"
				>
					<span class="custom-tree-node" slot-scope="{ data }">
						<span> <i :class="data.icon"></i>{{ data.cname }} </span>
					</span>
				</el-tree>
			</div>
		</div>
		<div class="right-container">
			<div class="top-right">
				<div class="control-buttons">
					<div class="radio-selectors">
						<el-radio
							v-model="radioValue"
							label="option1"
							style="color: #ccccccde"
							@change="handleRadioChange"
							>实时查询</el-radio
						>
						<el-radio
							v-model="radioValue"
							label="option2"
							style="color: #ccccccde; padding-right: 50px"
							@change="handleRadioChange"
							>时段查询</el-radio
						>
					</div>
					<div class="select-box">
						<div class="select-title">时间间隔：</div>
						<el-select
							v-model="selectValue"
							size="small"
							placeholder="请选择"
							:disabled="isDatePickerDisabled"
							style="height: 40px; margin-top: 0px"
						>
							<el-option
								v-for="item in options"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							>
							</el-option>
						</el-select>
						<div class="select-title">选择日期：</div>
						<el-date-picker
							v-model="dateRange"
							size="small"
							type="datetimerange"
							:default-time="['00:00:00', '23:59:59']"
							:default-value="defaultDateRange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							:disabled="isDatePickerDisabled"
							value-format="yyyy-MM-dd HH:mm:ss"
							@change="handleConfirm"
							:picker-options="pickerOptions"
						>
							></el-date-picker
						>
					</div>
				</div>
				<div class="buttons">
					<el-button
						class="custom-button-min-width"
						type="primary"
						size="small"
						@click="queryPointsData"
						>查询</el-button
					>
					<el-button
						class="custom-button-min-width"
						type="primary"
						size="small"
						@click="clearData"
						>重置</el-button
					>
				</div>
				<div class="chart-title">遥测运行曲线</div>
				<div :style="{ width: '100%', height: '430px' }">
					<meacurve
						:info="{ xData: xData, yData: yData1, lineName: lineName }"
					/>
				</div>
			</div>
			<div class="bottom-right">
				<div class="chart-title">
					<div class="title">遥测数据</div>
					<div class="buttons">
						<el-button
							v-show="xData.length > 0"
							class="custom-button-min-width"
							type="primary"
							size="small"
							@click="showData"
							>显示数据</el-button
						>
						<el-button
							v-show="tableData.length > 0"
							class="custom-button-min-width"
							type="primary"
							@click="exportData"
							size="small"
							>导出</el-button
						>
					</div>
				</div>

				<!-- <el-table style="width: '100%'; height: '40vh'; color:#ccccccde; background-color: #050614;" :data="tableData" row-class-name="custom-table-style"  stripe  height="380" border:true> -->
				<div class="table-container">
					<el-table :data="tableData" height="380px" border:true ref="myTable">
						<el-table-column
							v-for="column in tableCol"
							:key="column[0]"
							:prop="column[0]"
							:label="column[1]"
						>
						</el-table-column>
					</el-table>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { getmenu } from "@/api/modules/home";
import { ycList, ycInfo, ycInfoFromTime } from "@/api/modules/energyunit";
import meacurve from "./components/meacurve.vue";
import FileSaver from "file-saver";

export default {
	components: { meacurve },
	data() {
		const currentDate = new Date();
		const startDate = new Date(currentDate);
		startDate.setHours(0, 0, 0, 0);
		const endDate = new Date();
		return {
			treeData: [],
			//filteredTreeData: [],
			defaultProps: {
				id: "id",
				index: "index",
				name: "name",
				icon: "icon",
				cname: "cname",
				children: "children",
			},
			clickTreeNode: [],
			xData: [],
			yData1: [],
			lineName: [],
			tableCol: [],
			tableData: [],
			searchKey: "",
			dateRange: [startDate, endDate],
			defaultDateRange: [startDate, endDate],
			radioValue: "option1",
			selectValue: 1,
			treeIsExpand: true,
			isDatePickerDisabled: true,
			selPointCount: 0,
			strTreeData: "",
			options: [
				{
					value: 1,
					label: "15分钟",
				},
				{
					value: 2,
					label: "1小时",
				},
			],
			pickerOptions: {
             disabledDate: (time) => {
               return time.getTime() > Date.now();
             },
           },
		};
	},

	created() {
		this.getCD();
	},

	methods: {
		timestampToFormattedDate(dateString) {
			var date = new Date(dateString);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, "0");
			const day = String(date.getDate()).padStart(2, "0");
			const hour = String(date.getHours()).padStart(2, "0");
			const minute = String(date.getMinutes()).padStart(2, "0");
			const second = String(date.getSeconds()).padStart(2, "0");
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
		},
		handleConfirm(selectedDate) {
			let timeDiff =
				(Date.parse(selectedDate[1]) - Date.parse(selectedDate[0])) / 1000;
			if (timeDiff > 0 && timeDiff <= 24 * 60 * 60) {
				this.options = [
					{ value: 1, label: "15分钟" },
					{ value: 2, label: "1小时" },
				];
				this.selectValue = 1;
			} else if (timeDiff > 24 * 60 * 60 && timeDiff <= 7 * 24 * 60 * 60) {
				this.options = [
					{ value: 2, label: "1小时" },
					{ value: 3, label: "1天" },
				];
				this.selectValue = 2;
			} else if (timeDiff > 7 * 24 * 60 * 60 && timeDiff <= 30 * 24 * 60 * 60) {
				this.options = [
					{ value: 3, label: "1天" },
					{ value: 4, label: "1周" },
				];
				this.selectValue = 3;
			} else if (
				timeDiff > 30 * 24 * 60 * 60 &&
				timeDiff <= 12 * 30 * 24 * 60 * 60
			) {
				this.options = [
					{ value: 4, label: "1周" },
					{ value: 5, label: "1月" },
				];
				this.selectValue = 4;
			} else if (timeDiff > 12 * 30 * 24 * 60 * 60) {
				this.$message("时间间隔超过1年了！");
				let now = new Date();
				this.dateRange[1] = now.getTime();
				now.setHours(0, 0, 0, 0);
				this.dateRange[0] = now.getTime();
				this.options = [
					{ value: 1, label: "15分钟" },
					{ value: 2, label: "1小时" },
				];
				this.selectValue = 1;
			}
		},

		handleNodeClick(nodeData, node) {
			if (nodeData.type == 4 || nodeData.type == 5) {
				if (nodeData.children.length == 0) {
					ycList({ devId: nodeData.id }).then((res) => {
						if (res.code == 200) {
							res.data.forEach((item, index) => {
								const newChildNode = {
									id: item.devId,
									name: item.name,
									cname: item.ycName,
									index: index,
									type: 6,
								};
								nodeData.children.push(newChildNode); // 将新子节点添加到当前点击节点的子节点列表中
							});
							this.strTreeData = JSON.stringify(this.treeData);
						}
					});
				}
			} else if (nodeData.type == 6) {
				node.checked = !node.checked;
			}
		},
		getCD() {
			getmenu({ companyID: this.$store.state.oldUserInfo.companyId }).then(
				(res) => {
					this.treeData = res.data;
					for (let i = 0; i < this.treeData.length; i++) {
						this.setTreeNodeDisable(this.treeData[i]);
					}
					this.strTreeData = JSON.stringify(this.treeData);
				}
			);
		},
		setTreeNodeDisable(node) {
			if (node.children && node.children.length > 0) {
				for (let i = 0; i < node.children.length; i++) {
					this.setTreeNodeDisable(node.children[i]);
				}
			} else {
				node.disabled = true;
			}
		},
		getDayYCXX() {
			let self = this;
			let selectedNodes = this.$refs.treeNode.getCheckedNodes(); //最多显示10个

			//最多显示10个
			this.selPointCount = 0;
			for (
				let sel = 0;
				sel < selectedNodes.length && this.selPointCount < 10;
				sel++
			) {
				if (selectedNodes[sel].type != 6) {
					continue;
				}
				this.selPointCount++;
				let tempData = [];
				self.lineName.push(selectedNodes[sel].cname);
				ycInfo({
					devId: selectedNodes[sel].id,
					sampleName: selectedNodes[sel].name,
				}).then((res) => {
					let data = res.data;
					for (let index = 0; index < data.length; index++) {
						let element = data[index];
						if (sel == 0) {
							self.xData.push(element.date);
						}
						tempData.push(element.graphHisDTO ? element.graphHisDTO.value : ""); //实时有效功率
					}
					self.yData1.push(tempData);
				});
			}

			if (this.selPointCount == 0) {
				this.$message("请至少选择一个遥测点！");
			}
		},

		filterNodeInfo(node) {
			if (node.type == 4 || node.type == 5) {
				if (node.children) {
					let nNum = node.children.length;
					let newNode = [];
					for (let i = 0; i < nNum; i++) {
						let index = node.children[i].cname.indexOf(this.searchKey);
						if (index !== -1) {
							newNode.push(node.children[i]);
						}
					}
					node.children = newNode;
				}
			} else {
				if (node.type < 6 && node.children) {
					for (let i = 0; i < node.children.length; i++) {
						this.filterNodeInfo(node.children[i]);
					}
				}
			}
		},
		filterTree() {
			this.treeData = JSON.parse(this.strTreeData);
			console.log(this.treeData);
			for (let i = 0; i < this.treeData.length; i++) {
				this.filterNodeInfo(this.treeData[i]);
			}

			// 重新渲染树形控件
			// this.$refs.treeNode.setCheckedNodes([]);
			// this.$refs.treeNode.setSelectedNodes([]);
			//this.$refs.treeNode.store.reload();
		},

		traversalTreeNode(node) {
			if (node.children) {
				for (let i = 0; i < node.children.length; i++) {
					this.traversalTreeNode(node.children[i]);
				}
			}
			if (node.type == 4 || node.type == 5) {
				ycList({ devId: node.id }).then((res) => {
					if (res.code == 200) {
						node.children = [];
						res.data.forEach((item, index) => {
							const newChildNode = {
								id: item.devId,
								name: item.name,
								cname: item.ycName,
								index: index,
								type: 6,
							};
							node.children.push(newChildNode); // 将新子节点添加到当前点击节点的子节点列表中
						});
						this.strTreeData = JSON.stringify(this.treeData);
					}
				});
			}
		},
		//获取所有测点
		getPoints() {
			//先展开节点，否则无法添加
			this.treeIsExpand = true;
			for (
				let j = 0;
				j < this.$refs.treeNode.store._getAllNodes().length;
				j++
			) {
				this.$refs.treeNode.store._getAllNodes()[j].expanded =
					this.treeIsExpand;
			}
			for (let i = 0; i < this.treeData.length; i++) {
				this.traversalTreeNode(this.treeData[i]);
			}
		},
		//时间段查询
		getTimeYCXX() {
			let selectedNodes = this.$refs.treeNode.getCheckedNodes(); //最多显示10个
			this.selPointCount = 0;
			for (
				let sel = 0;
				sel < selectedNodes.length && this.selPointCount < 10;
				sel++
			) {
				if (selectedNodes[sel].type != 6) {
					continue;
				}
				let tempData = [];
				this.selPointCount++;
				this.lineName.push(selectedNodes[sel].cname);
				ycInfoFromTime({
					devId: selectedNodes[sel].id,
					sampleName: selectedNodes[sel].name,
					startDate: this.timestampToFormattedDate(this.dateRange[0]),
					endDate: this.timestampToFormattedDate(this.dateRange[1]),
					intervalType: this.selectValue,
				}).then((res) => {
					for (let index = 0; index < res.data.length; index++) {
						let element = res.data[index];
						if (sel == 0) {
							this.xData.push(element.date);
						}
						tempData.push(element.graphHisDTO ? element.graphHisDTO.value : ""); //实时有效功率
					}
					this.yData1.push(tempData);
				});
			}
			if (this.selPointCount == 0) {
				this.$message("请至少选择一个遥测点！");
			}
		},
		//查询测点数据
		queryPointsData() {
			let selectedNodes = this.$refs.treeNode.getCheckedNodes();
			if (selectedNodes <= 0) {
				this.$message("请至少选择一个遥测点！");
				return;
			}
			this.xData = [];
			this.yData1 = [];
			this.lineName = [];
			if (this.radioValue == "option1") {
				this.getDayYCXX();
			} else {
				this.getTimeYCXX();
			}
			this.tableCol = [];
			this.tableData = [];
		},
		//表格展示书数据
		showData() {
			if (this.yData1.length == 0) {
				return;
			}
			this.tableCol = [];
			this.tableCol.push(["time", "时间"]);
			for (let jjj = 0; jjj < this.selPointCount; jjj++) {
				this.tableCol.push(["value" + jjj, this.lineName[jjj]]);
			}
			this.tableData = [];
			for (let kkk = 0; kkk < this.xData.length; kkk++) {
				let tempData = {};
				tempData.time = this.xData[kkk];
				for (let i = 0; i < this.selPointCount; i++) {
					tempData["value" + i] = this.yData1[i][kkk];
				}
				this.tableData.push(tempData);
			}

			this.$nextTick(() => {
				// 确保DOM更新后，手动调整表格高度
				this.$refs.myTable.doLayout();
			});
		},
		//导出
		exportData() {
			if (this.tableData.length == 0) {
				this.$message("遥测数据列表为空！");
				return;
			}
			const headers = Object.keys(this.tableData[0]);
			let csvData = [];
			// 添加表头数据
			csvData.push(headers.join(","));
			// 遍历表格数据，逐行添加数据
			this.tableData.forEach((row) => {
				const values = headers.map((header) => row[header]);
				csvData.push(values.join(","));
			});

			const csvContent = csvData.join("\n");
			const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8" });
			FileSaver.saveAs(blob, "table_data.csv");
		},
		handleRadioChange() {
			if (this.radioValue == "option1") {
				this.isDatePickerDisabled = true;
			} else {
				this.isDatePickerDisabled = false;
			}
		},
		//重置数据
		clearData() {
			this.xData = [];
			this.yData1 = [];
			this.lineName = [];
			this.tableCol = [];
			this.tableData = [];
			this.treeData = this.treeData.map((item) => ({
				...item,
				checked: false,
			}));
		},
	},
	mounted() {
		//initChart();
	},
};
</script>

<style>
.layout-container {
	display: flex;
}

.left-container {
	width: 30%;
}

.right-container {
	width: 70%;
	padding-left: 30px;
	box-sizing: border-box;
}

.top-left {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
}

.bottom-left {
	flex: 1;
	margin-top: 10px;
}

.top-right {
	display: flex;
	flex-direction: column;
	align-items: left;
	margin-bottom: 10px;
}

.control-buttons {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.radio-selectors {
	display: flex;
	align-items: center;
	margin-right: 10px;
	justify-content: flex-start;
}
.select-box {
	margin-top: 6px;
}
.top-right .buttons {
	text-align: right;
	margin-bottom: 10px;
}
.buttons .el-button--primary,
.buttons .el-button--primary:focus,
.buttons .el-button--primary:hover {
	background-color: #045eed;
	border-color: #045eed;
}
.select-title {
	font-size: 14px;
	line-height: 32px;
	vertical-align: middle;
	color: #ccccccde;
	display: inline-block;
	margin-left: 20px;
}
.chart-title {
	font-size: 14px;
	font-weight: bold;
	margin-bottom: 5px;
	margin-right: 15px;
	color: #ccccccde;
	display: flex;
	justify-content: space-between;
}
.chart-title .title {
	line-height: 30px;
}
.bottom-right {
	background-color: #050614;
}

.table-title {
	font-size: 16px;
	font-weight: bold;
	margin-top: 10px;
	margin-bottom: 13px;
	color: #ccccccde;
}

.label-button-wrapper {
	display: flex;
	align-items: center;
	white-space: nowrap;
}

.point-list-label {
	margin-right: 5px;
	color: #ccccccde;
}

.tree-with-scroll {
	max-height: 920px;
	overflow-y: auto;
}
.tree-with-scroll.el-tree {
	background-color: #050614;
	color: #ccccccde;
}
.custom-button-min-width {
	min-width: 60px;
}
</style>
